<route lang="json5">
{
  style: {
    navigationBarTitleText: '停车缴费',
  },
}
</route>
<template>
  <view class="head">
    <image style="height: 400rpx" src="/static/images/car/car.png"></image>
  </view>
  <view>
    <view class="catianbox">
      <view class="matin">
        <view class="mypark">
          <image class="w-[30rpx] h-[30rpx]" src="/static/images/car/tc.png"></image>
          <view class="ml-[10rpx]">查看该停车场的停车记录</view>
        </view>
        <view class="flex booking mt-[40rpx] sold">
          <view>
            <view>车牌号码</view>
            <view class="font">{{ parkingdetails.plateNumber || 'xxxx' }}</view>
          </view>
          <view class="ebbf" @click="addcarp">查询停车信息</view>
        </view>

        <view class="flex booking mt-[40rpx] dash">
          <view>
            <view>停车费用</view>
            <view class="font">{{ parkingdetails.fee / 100 || 0 }}.00元</view>
          </view>
          <view>
            <view>停车时长</view>
            <view class="font">{{ formattedTime(parkingdetails.len) || '0天0时0分' }}</view>
          </view>
        </view>

        <view class="mt-[40rpx]">
          <view>停车地点</view>
          <view class="font-min">{{ parkingdetails.parkingName || '暂无信息' }}</view>
        </view>

        <view class="mt-[40rpx]">
          <view>入场时间</view>
          <view class="font-min">{{ parkingdetails.st || 0 }}</view>
        </view>
      </view>
    </view>

    <view class="footer" v-if="parkingdetails.parkingOrderId !== ''">
      <view class="flex">
        需缴费
        <view class="money">¥{{ parkingdetails.fee / 100 || 0 }}.00元</view>
      </view>
      <view>
        <view v-if="parkingdetails.isPrepay === 1" class="paybtn">已缴费</view>
        <view v-else-if="parkingdetails.fee === 0"></view>
        <view class="paybtn" @click="confirmpayment" v-else-if="parkingdetails.isPrepay === 0">
          确认支付
        </view>
      </view>
    </view>
  </view>
  <wd-popup closable custom-style="height: 200px;width:400px;" v-model="show">
    <view class="popup-content mt-6 w-full">
      <view class="sticky top-0 bg-white z-[99999]">
        <view class="font-bold mt-[100rpx]">请输入需要查询的车牌信息</view>
        <view class="font-bold">
          <wd-input type="text" v-model="msg" placeholder="" readonly @click="showKeyBoard" />
        </view>
        <view class="chaxun">
          <wd-button type="warning" @click="getche">查询车辆停车信息</wd-button>
        </view>
        <!-- <wd-cell title="车牌号键盘" is-link @click="showKeyBoard" /> -->
      </view>
    </view>
  </wd-popup>
  <!-- <wd-popup
    ref="wdModal"
    v-model="show"
    custom-style="height: 700rpx; width:500rpx;"
    negative-top="20"
    show-cancel-button
    title="车位信息"
    @cancel="closePopup"
    @confirm="confirm"
  > -->
  <!-- <view class="popup-content mt-6 w-full">
      <view class="flex items-center justify-between sticky top-0 bg-white z-[99999]">
        <text class="font-bold">选择预定车位数量</text>
        <u-number-box v-model="comParkingSpaceQuantitySize" :min="0" integer @change="updateParkingSpaceQuantity" />
      </view>
      <view v-for="(item, index) in parkingSpaceQuantity" :key="index">
        <view class="text-blue-400 font-bold mb-2 mt-2">车辆{{ index + 1 }}</view>
        <view class="flex items-center">
          <car-number-input :defaultStr="item" class="flex-1" @numberInputResult="numberInputResult($event, index)" />
          <text class="material-icons text-red-500" @click="deleteNumberInput(index)">cancel</text>
        </view>
      </view>
    </view> -->
  <!-- </wd-popup> -->
  <wd-keyboard v-model:visible="visible" mode="car" @input="onInput" @delete="onDelete" />
</template>

<script setup>
//车辆停车信息及停车缴费
import { findOrder, parkReadyPay } from '@/service/car/car' // 看这里
const {
  loading: carLoading,
  error: carError,
  data: carData,
  run: carRun,
} = useRequest(() => findOrder(formdata.value))

const {
  loading: parkLoading,
  error: parkError,
  data: parkData,
  run: parkRun,
} = useRequest(() => parkReadyPay(parkReadyPayData.value))

//查询用户一卡通id还有充值接口
import { getCardByUserId, topUp } from '@/service/card/card' // 看这里
const {
  loading: cardLoading,
  error: cardError,
  data: cardData,
  run: cardRun,
} = useRequest(() => getCardByUserId(userdata.value))
const {
  loading: topUpLoading,
  error: topUpError,
  data: topUpData,
  run: topUpRun,
} = useRequest(() => topUp(topupData.value))

const parkingSpaceQuantity = ref([]) // 车位数据

const parkingdetails = ref({
  isPrepay: 0,
  parkingOrderId: '',
})

const show = ref(false) // 弹出层
const parkingList = ref([])

import { useUserStore } from '@/store'
import { storeToRefs } from 'pinia'
const { userInfo } = storeToRefs(useUserStore())

//一卡通id
const cardId = ref('')

const userdata = ref({})
const topupData = ref({})

userdata.value.usrId = userInfo.value.id

const formdata = ref({
  code: 100,
  query: 0,
  plateNumber: '鄂A138QS',
})

const parkReadyPayData = ref({
  code: 100,
  parkingOrderId: '',
})

const visible = ref(false)

function showKeyBoard() {
  uni.hideKeyboard()
  visible.value = true
}

const msg = ref('')

const onInput = (value) => {
  msg.value += value
}
const onDelete = () => {
  msg.value = msg.value.slice(0, msg.value.length - 1)
}

const addcarp = () => {
  show.value = true
}

const getche = () => {
  formdata.value.plateNumber = msg.value
  findOrder(formdata.value)
    .then((res) => {
      // console.log('查询订单成功', res)
      if (res.code === 1401) {
        uni.navigateTo({
          url: '/pages/login/login',
        })
      } else if (res.code === 0) {
        parkingdetails.value = res.data
        show.value = false
      } else {
        uni.showToast({
          title: res.msg,
          duration: 2000,
          icon: 'none',
        })
      }
    })
    .catch((res) => {
      console.log('查询订单失败')
    })
}

// 转换天时分
const formattedTime = (time) => {
  const seconds = time
  const days = Math.floor(seconds / (24 * 60 * 60)) || 0 // 计算天数
  const hours = Math.floor((seconds % (24 * 60 * 60)) / (60 * 60)) || 0 // 计算小时数
  const minutes = Math.floor((seconds % (60 * 60)) / 60) || 0 // 计算分钟数
  return `${days}天 ${hours}小时 ${minutes}分钟` // 返回格式化后的字符串
}

const flag = ref(false)

onShow(() => {})

// 确认支付
const confirmpayment = () => {
  if (parkingdetails.value.parkingOrderId === '') {
    uni.showToast({
      title: '请先查询车辆停车信息', // 提示的内容
      icon: 'none', // 图标类型: success, loading, error
      duration: 2000, // 显示时间（毫秒），默认1500
    })
  } else {
    parkReadyPayData.value.parkingOrderId = parkingdetails.value.parkingOrderId
    parkReadyPay(parkReadyPayData.value).then((res) => {
      if (res.code === 1401) {
        uni.navigateTo({
          url: '/pages/login/login',
        })
      } else if (res.code === 123) {
        uni.showToast({
          title: '余额不足',
          duration: 1000,
          icon: 'none',
        })

        topupData.value = {
          cardId: cardId.value,
          inMoney: parkingdetails.value.fee,
          usrId: userInfo.value.id,
        }
        console.log(topupData)
        topUpRun().then((data) => {
          const payment = {
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.packageStr,
            signType: data.signType,
            paySign: data.paySign,
          }
          console.log(payment)
          wx.requestPayment({
            ...payment,
            success: function (resdata) {
              setTimeout(() => {
                parkReadyPay(parkReadyPayData.value).then((resdata) => {
                  if (resdata.code === 0) {
                    uni.showToast({
                      title: '缴费成功', // 提示的内容
                      icon: 'none', // 图标类型: success, loading, error
                      duration: 2000, // 显示时间（毫秒），默认1500
                    })
                    parkingdetails.value.isPrepay === 1
                  } else {
                    uni.showToast({
                      title: resdata.msg,
                      duration: 2000,
                      icon: 'none',
                    })
                  }
                })
              }, 500)
            },
            fail: function (error) {
              //  uni.navigateBack({ delta: 1 })
              uni.showToast({
                title: '支付失败',
                duration: 2000,
                icon: 'none',
              })
              console.log('支付失败')
              console.log(error)
            },
          })
        })

        // uni.navigateTo({
        //   url: '/pages/card/topup',
        // })
      } else if (res.code === 0) {
        uni.showToast({
          title: '缴费成功', // 提示的内容
          icon: 'none', // 图标类型: success, loading, error
          duration: 2000, // 显示时间（毫秒），默认1500
        })
        parkingdetails.value.isPrepay === 1
      } else {
        uni.showToast({
          title: res.msg,
          duration: 2000,
          icon: 'none',
        })
      }
    })
  }
}

// 关闭弹框
const closePopup = () => {
  show.value = false
  parkingSpaceQuantity.value = []
}

onLoad(() => {
  cardRun().then((res) => {
    cardId.value = res.id
  })
})
</script>

<style scoped>
.font-bold {
  padding-left: 40rpx;
}

.chaxun {
  padding-top: 60rpx;
  padding-left: 450rpx;
}

.catianbox {
  padding: 30rpx;
  background-color: #fafafa;
}

.matin {
  padding: 10rpx;
  background-color: #ffffff;
  border-radius: 15rpx;
}

.mypark {
  display: flex;
  align-items: center;
  padding: 15rpx;
  color: #ffbc80;
  background-color: #fbf1e8;
}

.font {
  font-size: 48rpx;
  font-weight: bold;
}

.booking {
  align-items: flex-end;
  justify-content: space-between;
}

.ebbf {
  display: flex;
  align-items: flex-end;
  color: #6aebbf;
}

.dash {
  padding-bottom: 30rpx;
  border-bottom: 5rpx dashed #f4f4f4;
}

.money {
  color: #d8767a;
}

.paybtn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 300rpx;
  height: 80rpx;
  color: #ffffff;
  background-color: #0063ff;
  border-radius: 40rpx;
}

.footer {
  display: flex;
  align-items: center;
  justify-content: space-around;
  height: 128rpx;
  box-shadow: 0 -4px 8px rgba(0, 0, 0, 0.1);
}

.font-min {
  font-size: 30rpx;
  font-weight: bold;
}

.head {
  display: flex;
  align-items: center;
  justify-content: center;
  padding-top: 185rpx;
  background: url('')
    no-repeat;
}

.sold {
  padding-bottom: 30rpx;
  border-bottom: 5rpx solid #f4f4f4;
}
</style>
